//   
//   CarouselView.swift
//   BaseComponetKit
//   Created  by monkey on 2024/4/2
//   

import UIKit
import SnapKit

class CarouselView: UIView {
    var currentPageDidChange: ((Int) -> Void)?

    private var collectionView: UICollectionView!
    private var images: [UIImage] = []
    private var timer: Timer?
    private var currentPage: Int = 1 {
        didSet {
            collectionView.setContentOffset(CGPoint(x: currentPage * Int(bounds.width), y: 0), animated: false)
            print("currentPage: \(currentPage - 1) offsetX: \(self.collectionView.contentOffset.x)")
            currentPageDidChange?(currentPage - 1)
            pageControl.currentPageIndicatorTintColor = images[currentPage].averageColorInCenter()


        }
    }
    private var pageControl: UIPageControl!
    private var flowLayout: UICollectionViewFlowLayout!
    private var didSelectItemHandler: ((Int) -> Void)? // 用于处理广告点击事件的闭包
    private var isDragging = false // 用于标记用户是否正在拖动轮播图

     init(frame: CGRect, images: [UIImage]) {
        super.init(frame: frame)
         DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in
             self?.setupCollectionView()
             self?.setupPageControl()
             self?.updateImage(images)
         }
    }
    
    
   public func updateImage(_ images: [UIImage]) {
       if images.isEmpty {
           return
       }

      self.images = images
       
       var adjustedImages = images
          if let firstImage = images.first {
              adjustedImages.append(firstImage)
          }
          // 在传入的图片数组的开头插入最后一个图像
          if let lastImage = images.last {
              adjustedImages.insert(lastImage, at: 0)
          }
          self.images = adjustedImages

       DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { [weak self] in
           self?.currentPage = 1       
           self?.pageControl.numberOfPages =  adjustedImages.count - 2
           self?.pageControl.currentPage = 0
           
           self?.collectionView.reloadData()
           self?.startAutoScroll()
           
       }
      

    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    
    private func setupCollectionView() {
        flowLayout = UICollectionViewFlowLayout()
        flowLayout.scrollDirection = .horizontal
        flowLayout.minimumLineSpacing = 0
        collectionView = UICollectionView(frame: bounds, collectionViewLayout: flowLayout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
        collectionView.isPagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        addSubview(collectionView)
        
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    private func setupPageControl() {
        pageControl = UIPageControl()
        addSubview(pageControl)
        pageControl.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-10)
        }
    }
    
    private func startAutoScroll() {
        timer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(scrollToNextPage), userInfo: nil, repeats: true)
    }
    
    @objc private func scrollToNextPage() {
        let nextPage = (currentPage + 1) % (images.count)
        let offsetX = CGFloat(nextPage) * collectionView.bounds.width


        if nextPage == images.count - 1 {
            // 从最后一个到第一个，应用渐变动画
            self.collectionView.setContentOffset(CGPoint(x: 0, y: 0), animated: false)
            self.collectionView.alpha = 0.9
            UIView.animate(withDuration: 0.5, delay: 0, options: [.curveEaseInOut], animations: {
                self.collectionView.alpha = 1.0
                // 动画执行完成后，滑动到第一个图片位置
                self.animateScrollToFirstPage(self.collectionView.bounds.width)
            }, completion: { _ in
                // 动画执行完成后，更新当前页码和页面控制器的当前页码
                self.currentPage = 1
                self.pageControl.currentPage = 0
            })
        } else {
            // 其他情况正常过渡
            animateScrollToOffset(offsetX)
            // 动画执行完成后，更新当前页码和页面控制器的当前页码
            self.currentPage = nextPage
            self.pageControl.currentPage = self.currentPage - 1
        }
    }

    private func animateScrollToOffset(_ offsetX: CGFloat) {
        let animationSteps = 60 // 动画步数
        let duration = 0.5 // 动画总时长
        
        var currentOffsetX = collectionView.contentOffset.x
        let stepOffsetX = (offsetX - currentOffsetX) / CGFloat(animationSteps)
        
        for step in 0..<animationSteps {
            DispatchQueue.main.asyncAfter(deadline: .now() + duration / Double(animationSteps) * Double(step)) {
                currentOffsetX += stepOffsetX
                self.collectionView.setContentOffset(CGPoint(x: currentOffsetX, y: 0), animated: false)
            }
        }
    }
    
    private func animateScrollToFirstPage(_ offsetX: CGFloat) {
        let animationSteps = 60 // 动画步数
        let duration = 0.5 // 动画总时长
        
        var currentOffsetX = collectionView.contentOffset.x
        let stepOffsetX = (offsetX - currentOffsetX) / CGFloat(animationSteps)

        for step in 0..<animationSteps {
            DispatchQueue.main.asyncAfter(deadline: .now() + duration / Double(animationSteps) * Double(step)) {
                currentOffsetX += stepOffsetX
                self.collectionView.setContentOffset(CGPoint(x: currentOffsetX, y: 0), animated: false)
            }
        }
    }
    // 广告点击事件处理
    private func handleAdClick(at index: Int) {
        didSelectItemHandler?(index - 1)
    }
    
    // 设置广告点击事件的闭包
    func didSelectItem(_ handler: @escaping (Int) -> Void) {
        didSelectItemHandler = handler
    }


}

extension CarouselView: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
        
        // 检查 cell 中是否已经存在 imageView
        if let imageView = cell.contentView.subviews.first as? UIImageView {
            // 如果存在，更新图像
            imageView.image = images[indexPath.item]
        } else {
            // 如果不存在，创建新的 imageView 并添加到 contentView 中
            let imageView = UIImageView(frame: cell.contentView.bounds)
            imageView.image = images[indexPath.item]
            imageView.contentMode = .scaleAspectFill
            imageView.clipsToBounds = true
            cell.contentView.addSubview(imageView)
        }
        
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return bounds.size
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
         // 广告被点击，调用处理方法
         handleAdClick(at: indexPath.item)
     }
    
    // 当用户开始拖动轮播图时，暂停定时器
     func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
         isDragging = true
         timer?.invalidate()
     }
    
    // 当用户停止拖动轮播图时，重新启动定时器
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        isDragging = false
        startAutoScroll()
    }
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
         // 计算当前页面索引
         let currentIndex = Int(scrollView.contentOffset.x / bounds.width)
         currentPage = currentIndex
         pageControl.currentPage = currentIndex - 1

        if currentPage == images.count - 1 {
                 // 如果当前页码为最后一页，则将currentPage和pageControl.currentPage设置为第一个索引
                 currentPage = 1
                 pageControl.currentPage = 0
                 // 滚动到第一个位置
            collectionView.setContentOffset(CGPoint(x: currentPage * Int(bounds.width), y: 0), animated: false)
             }
        
        if currentPage == 0 {
                 // 如果当前页码为最后一页，则将currentPage和pageControl.currentPage设置为第一个索引
                 currentPage = 3
                 pageControl.currentPage = 2
                 // 滚动到第一个位置
            collectionView.setContentOffset(CGPoint(x: currentPage * Int(bounds.width), y: 0), animated: false)
             }

     }
  
}
